package com.tiantian.subject.controller;

import com.tiantian.common.core.domain.ResponseResult;
import com.tiantian.common.core.exception.BusinessException;
import com.tiantian.common.satoken.domain.controller.BaseController;
import com.tiantian.subject.domain.dto.MergeChunksDto;
import com.tiantian.subject.service.QuestionBankFileUploadService;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author tiantian
 */
@RestController
@RequestMapping("/questionBank/file")
@RequiredArgsConstructor
public class QuestionBankFileUploadController extends BaseController {

    private final QuestionBankFileUploadService questionBankFileUploadService;

    /**
     * 小文件上传
     */
    @PostMapping("/upload/smallFile")
    public ResponseResult<Void> uploadSmallFile(@RequestPart("file") MultipartFile file, @NotNull(message = "当前路径不能为空") String curPath) {
        if (file.isEmpty()) return ResponseResult.fail("文件大小不能为空");
        checkFileSize(file.getSize());
        boolean res = questionBankFileUploadService.uploadSmallFile(file, curPath);
        return toAjax(res);
    }


    /**
     * 文件上传前检查文件
     */
    @PostMapping("/upload/checkFile")
    public ResponseResult<Void> checkFile(@NotNull(message = "文件的MD5值不能为空") String fileMd5) {
        boolean fileExist = questionBankFileUploadService.checkFileExist(fileMd5);
        return toAjax(fileExist);
    }

    /**
     * 分块文件上传前的检测
     */
    @PostMapping("/upload/checkChunk")
    public ResponseResult<Void> checkChunk(@NotNull(message = "文件的MD5值不能为空") String fileMd5,
                                           @NotNull(message = "当前分片索引不能为空") int chunk) {
        boolean checkChunkExist = questionBankFileUploadService.checkChunkExist(fileMd5, chunk);
        return toAjax(checkChunkExist);
    }

    /**
     * 上传分块文件
     */
    @PostMapping("/upload/uploadChunk")
    public ResponseResult<Void> uploadChunk(MultipartFile file,
                                            @NotNull(message = "文件的MD5值不能为空") String fileMd5,
                                            @NotNull(message = "当前分片索引不能为空") int chunk) {
        if (file.isEmpty()) return ResponseResult.fail("文件大小不能为空");
        checkFileSize(file.getSize());
        boolean isOk = questionBankFileUploadService.uploadChunk(file, fileMd5, chunk);
        return toAjax(isOk);
    }

    /**
     * 合并文件
     */
    @PostMapping("/upload/mergeChunks")
    public ResponseResult<Void> mergeChunks(@Validated @RequestBody MergeChunksDto mergeChunksDto) {
        boolean isOk = questionBankFileUploadService.mergeChunks(mergeChunksDto);
        return toAjax(isOk);
    }

    private void checkFileSize(long size) {
        if (size > 1024 * 1024 * 10) {
            throw new BusinessException("文件大小不能超过10M");
        }
    }
}
